﻿using System;
using OverStore.Configuration.Validation;
using OverStore.Exceptions.Configuration;
using OverStore.Runtime.OverStoreContext;
using OverStore.Runtime.ObjectRepository.Depot.IdentifierGenerator;

namespace OverStore.Configuration.ObjectRepository.Depot.IdentifierGenerator
{
    
    /// <summary>
    /// Contains configuration parameters allows to create new instances of <see cref="DelegateIdentifierGenerator{TInstance, TIdentifier}"/>
    /// </summary>
    /// <typeparam name="TInstance">The type of the instance.</typeparam>
    /// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
    public sealed class DelegateGeneratorConfiguration<TInstance, TIdentifier> : IComponentConfiguration<IIdentifierGenerator<TInstance, TIdentifier>>,
        ISupportValidation
        where TInstance : class
    {
        /// <summary>
        /// Gets or sets the delegate generates next identifier using instance and last generated identifier.
        /// </summary>
        public Func<TInstance, TIdentifier, TIdentifier> NextIdentifierFunc { get; set; }

        /// <summary>
        /// Gets or sets the starting result of identifier.
        /// </summary>
        public TIdentifier StartingValue { get; set; }

        /// <summary>
        /// Creates the new instance of <see cref="IIdentifierGenerator{TInstance, TIdentifier}"/> with specified configuration.
        /// </summary>
        /// <param name="context">The context provides set of services may be useful for new instance of identifier generator.</param>
        /// <returns>
        /// The new instance of <see cref="IIdentifierGenerator{TInstance, TIdentifier}"/>.
        /// </returns>
        public IIdentifierGenerator<TInstance, TIdentifier> CreateComponent(IOverStoreContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (NextIdentifierFunc == null)
                throw this.ConfigurationException("Next Identifier Func is missing.");
            return new DelegateIdentifierGenerator<TInstance, TIdentifier>(NextIdentifierFunc, StartingValue);
        }

        /// <summary>
        /// Perform component validation. Method should validate only
        /// component configuration itself, not sub components.
        /// If configuration is valid, null result should returns.
        /// </summary>
        /// <returns>
        ///     <see cref="T:OverStore.Configuration.ValidationResults"/> describes errors found in component configuration.
        /// </returns>
        public ValidationResult Validate()
        {
            return new ValidationResult(this)
                .AddError(NextIdentifierFunc == null, "Next Identifier Function is missing.");
        }
    }
}
